<?php

namespace app\api\model\service;

use think\App;
use think\Model;
use traits\model\SoftDelete;
use think\Exception;
use fast\Random;
class Order extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'service_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    /**
     * 项目结算
     * @param $param
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function settle($params)
    {
        $goods = Goods::where(['id' => $params['goods_id'], 'status' => 'normal'])->field('id,image,response_hour,start_hour,end_hour,shop_id,name,type,price,cost_seconds,to_shop,is_travel,choose_skill_type')->find();
        if (!$goods) {
            throw new Exception('项目信息异常,无法下单');
        }
        $data['goods'] = $goods;
        $data['sumprice'] = bcmul($goods['price'], $params['num'], 2);
        $data['shop'] = $goods['type'] == 1 ? Shop::getShop($goods['shop_id']) : '';
        if ($params['goods_sku_id']) {
            $goodsSku = GoodsSku::where(['id' => $params['goods_sku_id'], 'goods_id' => $goods['id'], 'status' => 'normal'])->field('id,name,price,cost_seconds')->find();
            if (!$goodsSku['id']) {
                throw new Exception('规格信息异常');
            }
            $data['goodsSku'] = $goodsSku;
            $goods['price'] = $goodsSku['price'];
            $data['sumprice'] = sprintf("%.2f", $data['goodsSku']['price'] * $params['num']);
        }
        return $data;
    }


    /**
     * 创建订单
     * @param $params
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function createOrder($params)
    {
        $goods = self::settle($params);
        $userInfo = UserInfo::where(['user_id' => $params['user_id']])->field('discount,is_plus')->find();
        $data = ['user_id' => $params['user_id'],'goods_id'=>$goods['goods']['id'],'discount'=>$userInfo['discount'],'city'=>$params['city'],'traveltype' => $params['traveltype'], 'travel_price' => $params['travel_price'],'distance'=>$params['distance'], 'choose_skill_type' => $params['choose_skill_type'], 'paytype' => $params['paytype'], 'to_shop' => $params['to_shop'], 'orderId' => 'GoodsOrd' . Random::alnum(4) . '-' . $params['user_id'] . '-' . time(), 'memo' => $params['memo']];
        if($params['shop_id'])
        {
            $data['shop_id'] = $params['shop_id'];
        }elseif($goods['goods']['shop_id']){
            $data['shop_id'] = $goods['goods']['shop_id'];
        }
        $data['total_cost_seconds'] = isset($goods['goodsSku']) ? intval($goods['goodsSku']['cost_seconds'] * $params['num']) : intval($goods['goods']['cost_seconds'] * $params['num']);

        $price = isset($goods['goodsSku']) ? $goods['goodsSku']['price'] : $goods['goods']['price'];

        $data['price'] = bcmul($price, $params['num'], 2);
        $data['sumprice'] = bcadd($data['price'], $params['travel_price'], 2);
        $data['goods_total_price'] = $userInfo['discount'] < 100 ?round(bcmul($data['price'], $userInfo['discount']/100, 3),2) : $data['price'];
        $data['payprice'] = $userInfo['discount'] < 100?bcadd($data['goods_total_price'],$params['travel_price'],3):$data['sumprice'];
        if (!strstr($goods['goods']['to_shop'], $params['to_shop'])) {
            throw new Exception('当前服务并无所选出行方式');
        }
        $needtime = $data['total_cost_seconds'] * 60;
        if($params['to_shop'] == 'shop' && $params['skill_id'])
        {
            $params['skill_id'] = '';
        }
        if ($params['skill_id']) {

            $skill = Skill::skillInfo($params['skill_id']);
            if($skill['is_rest'] == 1)
            {
                throw new Exception('服务者休息中,无法预约');
            }
            $data['skill_id'] = $skill['id'];
            $data['shop_id'] = $skill['shop_id'];
            $data['choose_skill_type'] = 1;
            $timeInfo = SkillTime::where(['skill_id' => $params['skill_id'], 'id' => $params['time_id'], 'state' => 0])->field('id,starttime')->find();
            if (!$timeInfo) {
                throw new Exception('当前时间已占用,无法预约');
            }
            $data['starttime'] = $timeInfo['starttime'];
            $data['endtime'] = $timeInfo['starttime'] + $needtime;
            $data['actendtime'] = $data['endtime'] + 1799;
            $timeExist = SkillTime::where(['state' => ['>', 0], 'skill_id' => $params['skill_id'], 'starttime' => ['between', [$data['starttime'], $data['actendtime']]]])->value('id');
            if ($timeExist) {
                throw new Exception('当前时间区间有被预约,请更换其他时间区间');
            }
        } elseif ($params['starttime']) {
            if ($params['starttime'] < time()) {
                throw new Exception('选择时间不可小于当前时间');
            }
            $data['starttime'] = $params['starttime'];
            $data['endtime'] = $params['starttime'] + $needtime;
            $data['actendtime'] = $data['endtime'] + 1799;
        }

        if ($params['coupon_id']) {
            $coupon = UserCoupon::checkCoupon($params['coupon_id'], $goods);
            if (!$coupon) {
                throw new Exception('优惠券无法使用');
            }
            $data['coupon_id'] = $params['coupon_id'];
            $data['coupon_price'] = sprintf("%.2f", $coupon['reduce']);
            $data['payprice'] = bcsub($data['payprice'], $data['coupon_price'],2);
        }
        if(empty($data['shop_id']) && empty($params['skill_id']))
        {
            $data['is_pool'] = 1;
        }
        $userMoney = User::getMoney($params['user_id']);
        if ($params['paytype'] == 4 && $userMoney < $data['payprice']) {
            throw new Exception('余额不足,请及时充值');
        }
        $order = new Order($data);
        $order->allowField(true)->save();
        OrderLog::create(['order_id' => $order->id, 'user_id' => $params['user_id'], 'content' => '用户创建订单成功']);
        if ($params['to_shop'] == 'door' && $params['address_id']) {
            $address = Address::where(['id' => $params['address_id']])->field('name,sex,mobile,province,city,district,address,lng,lat,area')->find()->toArray();
            if($params['skill_id'])
            {
                $skillCity = Skill::where('id',$params['skill_id'])->value('city');
                if($skillCity != $address['city'])
                {
                    throw new Exception('上门地址请选择服务者所在城市');
                }
            }

            $address['user_id'] = $params['user_id'];
            $address['order_id'] = $order->id;
            OrderAddress::create($address);
        }
        $sku_name = isset($goods['goodsSku']) ? $goods['goodsSku']['name'] : '';
        $detailData = ['user_id' => $params['user_id'], 'order_id' => $order->id, 'goods_id' => $params['goods_id'], 'goods_sku_id' => $params['goods_sku_id'], 'skill_id' => $params['skill_id'], 'name' => $goods['goods']['name'], 'image' => $goods['goods']['image'], 'num' => $params['num'], 'sku_name' => $sku_name, 'price' => $price, 'sumprice' => $data['sumprice']];
        $orderDetail = new OrderDetail($detailData);
        $orderDetail->allowField(true)->save();
        $re = [];
        if (in_array($params['paytype'], [0, 1, 2, 3])) {
            $re['pay'] = \addons\service\library\Pay::payOrder(['amount' => $data['payprice'], 'orderid' => $data['orderId'], 'title' => '支付项目费用'], $params['paytype'], $params['user_id'], 0);
        } elseif ($params['paytype'] == 4) {
            User::money(-$data['payprice'], $data['user_id'], '支付' . $goods['goods']['name'] . '项目费用');
            $order->save(['status' => 1, 'paytime' => time()], ['id' => $order->id]);
            $re['pay'] = '';
            self::finishPay($order->id);
        }
        return $re;
    }


    public static function pay($params)
    {
        $order = self::where(['id'=>$params['id'],'status'=>0,'user_id'=>$params['user_id']])->field('id,skill_id,shop_id,goods_id,payprice,user_id,to_shop,starttime,actendtime,coupon_id')->find();
        if(!$order)
        {
            throw new Exception('订单已超时,无法支付');
        }
        $orderDetail = OrderDetail::where(['order_id'=>$order['id']])->field('goods_id,goods_sku_id,price,name')->find();
        $price = $orderDetail['goods_sku_id'] ?GoodsSku::where(['id'=>$orderDetail['goods_sku_id'],'status'=>'normal'])->value('price'):Goods::where(['id'=>$order['goods_id'],'status'=>'normal'])->value('price');
        if(!$price || $price!=$orderDetail['price'])
        {
            throw new Exception('订单项目信息发生变化,请重新下单');
        }
        if ($order['coupon_id']) {
            $couponState = UserCoupon::where(['id'=>$order['coupon_id'],'user_id'=>$order['user_id']])->value('state');
            if ($couponState!=0) {
                throw new Exception('优惠券无法使用,请重新下单');
            }
        }
        if($order['starttime']<time())
        {
            throw new Exception('预约时间已超出,请重新下单');
        }
        if($order['skill_id'])
        {
            $skill = Skill::where(['id'=>$order['skill_id'],'state'=>1])->value('id');
            if(!$skill)
            {
                throw new Exception('当前服务者暂时无法接单,请重新下单');
            }
            $timeExist = SkillTime::where(['state' => ['>', 0], 'skill_id' => $order['skill_id'], 'starttime' => ['between', [$order['starttime'], $order['actendtime']]]])->value('id');
            if ($timeExist) {
                throw new Exception('当前服务者时间区间有被预约,请重新下单');
            }
        }
        $userMoney = User::getMoney($order['user_id']);
        if ($params['paytype'] == 4 && $userMoney < $order['payprice']) {
            throw new Exception('余额不足,请及时充值');
        }
        $orderId = 'GoodsOrd' . Random::alnum(4) . '-' . $params['user_id'] . '-' . time();
        self::where(['id'=>$order['id']])->update(['orderId'=>$orderId,'paytype'=>$params['paytype']]);
        $re = [];
        if (in_array($params['paytype'], [0, 1, 2, 3])) {
            $re['pay'] = \addons\service\library\Pay::payOrder(['amount' => $order['payprice'], 'orderid' => $orderId, 'title' => '支付项目费用'], $params['paytype'], $params['user_id'], 0);
        } elseif ($params['paytype'] == 4) {
            User::money(-$order['payprice'], $params['user_id'], '支付' .$orderDetail['name']. '项目费用');
            $order->save(['status' => 1, 'paytime' => time()], ['id' => $order['id']]);
            $re['pay'] = '';
            self::finishPay($order['id']);
        }
        return $re;

    }

    public static function allocationOrder($params)
    {
        $order = self::where(['id'=>$params['id'],'shop_id'=>$params['shop_id'],'status'=>1,'is_service'=>['in',[0,-1]]])->field('id,user_id,to_shop,starttime,actendtime,is_service,status')->find();
        if($order['to_shop'] != 'door' || !$order)
        {
            throw new Exception('当前订单无法分配服务者');
        }
        $skillId = Skill::where(['id'=>$params['skill_id'],'state'=>1])->value('id');
        if(!$skillId)
        {
            throw new Exception('当前服务者无法接单');
        }
        $exist = SkillTime::where(['skill_id'=>$skillId,'state'=>['in',[1,2]],'starttime'=>['between',[$order['starttime'],$order['actendtime']]]])->value('id');
        if($exist)
        {
            throw new Exception('当前服务者时间有被预约');
        }
        \app\api\model\service\SkillTime::updateSkillTime(['skill_id'=>$params['skill_id'],'starttime'=>$order['starttime'],'actendtime'=>$order['actendtime']],1);
        OrderLog::create(['order_id'=>$order['id'],'type'=>14,'content'=>'订单已分配','user_id'=>$order['user_id']]);
        self::where(['id'=>$order['id']])->update(['skill_id'=>$skillId]);
        $skillOpenid = UserInfo::getOpenid($params['skill_id'],1);
        self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>1,'templateAttr'=>'skill_order_template','openid'=>$skillOpenid]);
        return true;
    }

    public static function finishPay($id)
    {
        $order = self::where(['id'=>$id,'status'=>1])->find();
        if(!$order)
        {
            return false;
        }
        if($order['skill_id'])
        {
            SkillTime::updateSkillTime($order,1);
        }
        if($order['coupon_id']){
            UserCoupon::where('id',$order['coupon_id'])->update(['state'=>1,'updatetime'=>time()]);
        }
        if($order['to_shop'] == 'shop')
        {
            $update['status'] = 2;
            $update['check_name'] = time().$order['id'];
            $update['qrcode_image'] = \addons\service\library\Common::createQrcode($update['check_name']);
        }
        $update['act_travel_price'] = sprintf("%.2f",$order['travel_price']);
        self::where(['id'=>$id])->update($update);
        OrderLog::create(['order_id'=>$id,'user_id'=>$order['user_id'],'type'=>1,'content'=>'用户订单已支付']);
        Goods::where('id',$order['goods_id'])->setInc('salenums');
        if($order['skill_id'])
        {
            $skillOpenid = UserInfo::getOpenid($order['skill_id'],1);
            self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>1,'templateAttr'=>'skill_order_template','openid'=>$skillOpenid]);
        }
        if($order['shop_id'])
        {
            $shopOpenid = UserInfo::getOpenid($order['shop_id'],2);
            self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_order_template','openid'=>$shopOpenid]);
        }
        return true;
    }

    public static function getTotalAccept($params)
    {

        extract($params);
        $where['status'] = ['>',1];
        if(isset($skill_id) && $skill_id != '')
        {
            $where['skill_id'] = $skill_id;
        }
        if(isset($shop_id) && $shop_id != '')
        {
            $where['shop_id'] = $shop_id;
        }
        $starttime = strtotime(date("Y-m-d",$starttime));
        $where['starttime'] = ['>=',$starttime];
        return self::where($where)->count();
    }


    /**
     * 查询订单列表s
     * @param $params
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOrderList($params)
    {
        extract($params);
        $order = 'createtime desc';
        $where['is_service'] = ['<',1];
        if (isset($status) && $status != '') {
            $where['status'] = $status;
        }
        if (isset($city) && $city != '') {
            $where['city'] = $city;
        }
        if (isset($is_pool) && $is_pool != '') {
            $where['is_pool'] = $is_pool;
            $where['status'] = ['>',0];
        }
        if (isset($finish) && $finish == 1) {
            $where['status'] = ['in',[6,7]];
        }
        if (isset($not_in_finish) && $not_in_finish == 1) {
            $where['status'] = ['in',[1,2,3,4]];
        }
        if (isset($not_accept) && $not_accept == 1) {
            $where['status'] = 1;
            $where['skill_id'] = ['neq',''];
        }
        if (isset($not_allocation) && $not_allocation == 1) {
            $where['status'] = 1;
            $where['skill_id'] = ['null',''];
        }
        if (isset($not_finish) && $not_finish == 1) {
            $where['status'] = ['in',[2,3,4,5]];
        }
        if (isset($finish) && $finish == 1) {
            $where['status'] = ['in',[6,7]];
        }
        if (isset($in_service) && $in_service == 1) {
            $where['is_service'] = ['in',[1,2,-1]];
        }
        if (isset($user_id) && $user_id != '') {
            $where['user_id'] = $user_id;
        }
        if(isset($is_all) && $is_all != '')
        {
            $where['is_service'] = ['in',[1,2,0,-1]];
        }
        if(isset($goods_ids) && $goods_ids != '')
        {
            $where['goods_id'] = ['in',$goods_ids];
            
        }
        if(isset($shop_id) && $shop_id != '')
        {
            $where['shop_id'] = $shop_id;
        }
        if(isset($skill_id) && $skill_id != '')
        {
            $where['skill_id'] = $skill_id;
        }
        if(isset($is_service) && $is_service != '')
        {
            $where['is_service'] = $is_service;
        }
        if(isset($category_ids) && $category_ids != '')
        {
            $goods_ids = \app\admin\model\service\Goods::where(['category_id'=>['in',$category_ids]])->column('id');
            $where['goods_id'] = ['in',$goods_ids];
        }
        if(isset($skill_goods_ids) && $skill_goods_ids != '')
        {
            $goods_ids = \app\admin\model\service\Goods::where(['two_category_id'=>['in',$skill_goods_ids]])->column('id');
            $where['goods_id'] = ['in',$goods_ids];
        }
        
        $list = self::where($where)->field('id,user_id,skill_id,shop_id,payprice,status,refund_price,is_service,starttime,price,total_cost_seconds,to_shop,memo,is_settle')->order($order)->page($page)->limit(10)->select();

        foreach ($list as &$value)
        {
            $value['user'] = User::where(['id'=>$value['user_id']])->field('id,nickname,avatar')->find();
            $value['address'] = OrderAddress::where(['order_id'=>$value['id']])->find();
            $value['orderDetail'] = OrderDetail::where(['order_id'=>$value['id']])->field('goods_id,name,image,sku_name,num,price')->find();
            $value['shopName'] = $value['shop_id']?Shop::where('id',$value['shop_id'])->field('name,logo_image,trade_hour')->find():'';
            $value['skillInfo'] = $value['skill_id']?Skill::getOrderSkill($value['skill_id']):'';
            $value['refundInfo'] = $value['is_service'] != 0?RefundOrder::where(['order_id'=>$value['id']])->field('refund_reason,refund_price,content,note')->order('id desc')->find():'';
        }
        return $list;
    }

    public static function searchSettleOrder($params)
    {
        extract($params);
        $order = 'finishtime desc';
        $where['is_settle'] = ['>',0];
        $rebateWhere = ['user_id'=>$user_id,'type'=>$type,'rebatetype'=>['<>',2]];
        if(isset($shop_id))
        {
            $where['shop_id'] = $shop_id;
        }
        if(isset($skill_id) && $skill_id != '')
        {
            $where['skill_id'] = $skill_id;
        }
        if(isset($types))
        {
            $where['shop_id'] = $types == 0?['null','']:['not null',''];
        }
        if(isset($is_settle) && $is_settle != '')
        {
            $where['is_settle'] = $is_settle;
        }
        if(isset($starttime) && isset($endtime))
        {
            $where['finishtime'] = ['between',[$starttime,$endtime]];
            $rebateWhere['createtime'] = ['between',[$starttime,$endtime]];
        }
        $list = self::where($where)->field('id,user_id,skill_id,shop_id,payprice,status,is_settle,is_service,starttime,sumprice,coupon_price,premium_price,add_price,act_travel_price,refund_price,settle_price,total_cost_seconds,memo,orderId,createtime,finishtime')->order($order)->page($page)->limit(10)->select();
        foreach ($list as $key=>$value)
        {
            $list[$key]['orderDetail'] = OrderDetail::where(['order_id'=>$value['id']])->field('goods_id,name,image,sku_name,num,price')->find();
            $list[$key]['rebatePrice'] = Rebate::where(['order_id'=>$value['id'],'type'=>$type,'rebatetype'=>['<>',2]])->value('num');
            $list[$key]['skill'] = $value['skill_id']?Skill::where('id',$value->skill_id)->field('name,image')->find():'';
        }
        $orderIds = self::where($where)->column('id');
        $rebateWhere['order_id'] = ['in',$orderIds];
        $sumPrice = sprintf("%.2f",Rebate::where($rebateWhere)->sum('num'));
        return ['sumPrice'=>$sumPrice,'list'=>$list];
    }

    public static function getShopSkillOrder($params)
    {
        extract($params);
        $order = 'createtime desc';
        if(isset($shop_id) && $shop_id != '')
        {
            $where['shop_id'] = $shop_id;
        }
        if(isset($id) && $id != '')
        {
            $where['skill_id'] = $id;
        }
        if((isset($starttime) && $starttime != '') && (isset($endtime) && $endtime != ''))
        {
            $where['createtime'] = ['between',[$starttime,$endtime]];
        }
        $list = self::where($where)->field('id,user_id,skill_id,shop_id,payprice,status,is_settle,is_service,starttime,sumprice,coupon_price,premium_price,add_price,act_travel_price,refund_price,settle_price,total_cost_seconds,memo,orderId,createtime,finishtime')->order($order)->page($page)->limit(10)->select();
        foreach ($list as $key=>$value)
        {
            $list[$key]['address'] = OrderAddress::where(['order_id'=>$value['id']])->field('name,sex,mobile,province,city,district,address,area,lng,lat')->find();
            $list[$key]['orderDetail'] = OrderDetail::where(['order_id'=>$value['id']])->field('goods_id,name,image,sku_name,num,price')->find();
        }
        return $list;
    }


    public static function getOrderCount($params)
    {
        return self::where($params)->count();
    }
    public static function getOrderPrice($params,$attr)
    {
        return self::where($params)->sum($attr);
    }

    public static function getOrder($params)
    {
        return self::where($params)->field('id,payprice,starttime,status')->with('detail')->order('id desc')->select();
    }

    public static function getSkillOrderCount($params)
    {
        $start= strtotime(date("Y-m-d",time()));
        $endTime = $start+86399;
        for($a = 0;$a <= 2; $a++){
            $params['starttime'] = ['between',[86400*$a+$start,86400*$a+$endTime]];
            $week['date'] = date("Y-m-d",86400*$a+$start);
            $week['count'] = self::where($params)->count();
            $list[] = $week;
        }
        return $list;
    }

    public static function getTotalOrder()
    {
        $daytime = strtotime(date("Y-m-d",time()));
        $start= $daytime-86400*6;
        $end = $daytime;
        $day = [];
        $orderTotal = [];
        $total = ceil(($end-$start)/86400);;
        for($a = 0;$a <=$total; $a++){
            $where['finishtime'] = ['between',[86400*$a+$start,86400*$a+86399+$start]];
            $where['status'] = ['>',5];
            $day[] = date("m-d",86400*$a+$start);
            $orderTotal[] = self::where($where)->count();
        }
        return ['day'=>$day,'total'=>$orderTotal];
    }

    public static function getForm($params)
    {
        $daytime = strtotime(date("Y-m-d",time()));
        extract($params);
        $start= isset($starttime)?$starttime:$daytime-86400*6;
        $end = isset($endtime)?$endtime:$daytime;
        $total = ceil(($end-$start)/86400);
        if(isset($shop_id) && $shop_id != '')
        {
            $where['shop_id'] = $shop_id;
        }
        if(isset($skill_id) && $skill_id == 1)
        {
            $where['skill_id'] = $skill_id;
        }
        $where['status'] = ['>',5];
        $list = [];

        for($a = 0;$a <=$total; $a++){
            $where['finishtime'] = ['between',[86400*$a+$start,86400*$a+$start+86399]];
            $week['date'] = date("Y-m-d",86400*$a+$start);
            $week['price'] = sprintf("%.2f",self::where($where)->sum('price'));
            $week['count'] = self::where($where)->count();
            $list[] = $week;
        }
        return $list;
    }



    /**
     * 获取近3天订单数量
     * @param $params
     * @return array
     * @throws Exception
     */
    public static function getDayServiceList($params)
    {
        $daytime = strtotime(date("Y-m-d",time()));
        $list = [];
        for ($a = 0; $a < 3; $a++)
        {
            $starttime = $a>0 ?$a*86400+$daytime:$daytime;
            $endtime = $starttime+86399;
            $params['starttime'] = ['between',[$starttime,$endtime]];
            $day['time'] = $starttime;
            $day['orderCount'] = self::where($params)->count();
            $list[] = $day;
        }
        return $list;
    }

    public static function getCount($params)
    {
        $where['user_id'] = $params['user_id'];
        $where['is_service'] = ['in',[0,-1]];
        $where['status'] = 0;
        $data['unpayCount'] = self::where($where)->count();
        $where['status'] = ['in',[1,2,3,4]];
        $data['unServiceCount'] = self::where($where)->count();
        $where['status'] = 5;
        $data['serviceCount'] = self::where($where)->count();
        $where['status'] = 6;
        $data['notCommentCount'] = self::where($where)->count();
        unset($where['status']);
        $where['is_service'] = 1;
        $data['refundCount'] = self::where($where)->count();
        return $data;
    }


    public static function getOrderInfo($id)
    {
        $where = [
            'id' => $id,
        ];
        $order = self::where($where)->field('id,user_id,skill_id,shop_id,traveltype,check_name,refund_price,choose_skill_type,paytype,to_shop,orderId,discount,is_settle,price,travel_price,distance,sumprice,coupon_price,premium_price,add_price,payprice,total_cost_seconds,starttime,endtime,memo,qrcode_image,is_service,status,createtime,paytime')
            ->order('id desc')->find();
        $order['adddetail'] = AddOrder::getOrderDetailList($id);
        $order['detail'] = OrderDetail::where(['order_id'=>$order['id']])->find();
        $order['orderAddress'] = $order['to_shop'] == 'door'?OrderAddress::where(['order_id'=>$id])->find():'';
        $order['orderLog'] = OrderLog::where(['order_id'=>$id])->field('id,type,createtime,content')->order('id desc')->select();
        $order['shopInfo'] = $order['shop_id']?Shop::getShop($order['shop_id']):'';
        $order['skillInfo'] = $order['skill_id']?Skill::getOrderSkill($order['skill_id']):'';
        return $order;
    }

    public static function getTemplateOrderInfo($id)
    {
        $order = db('service_order')->where('id',$id)->field('skill_id,to_shop,orderId,memo as note,status,starttime as time,payprice as price')->find();
        $order['cate'] = OrderDetail::where('order_id',$id)->value('name');
        $order['address'] = $order['to_shop'] == 'door'?implode('',db('service_order_address')->where(['order_id'=>$id])->field('district,address')->find()):'到店服务';
        $order['status'] = self::getStatus($order['status']);
        $order['name'] = $order['skill_id']?Skill::where('id',$order['skill_id'])->value('name'):'';
        return $order;
    }


    public static function getStatus($status)
    {
        $statusAttr = ['待支付','待接单','待出发','已出发','已到达','开始服务','已完成','已评价'];
        return $status == -1?'已取消':$statusAttr[$status];
    }


    public static function shopAccept($order)
    {
        if(!$order)
        {
            throw new Exception('当前订单无法选取接单,请联系管理员');
        }
        OrderLog::create(['order_id'=>$order['id'],'user_id'=>$order['user_id'],'type'=>15,'content'=>'订单已被商户接取']);
        $update['status'] = 1;
        $update['is_pool'] = 0;
        $update['shop_id'] = $order['shop_id'];
        self::where(['id'=>$order['id']])->update($update);
        Shop::where('id',$order['shop_id'])->setInc('salenums');
        return true;
    }

    public static function createComplaintTemplateParams($params)
    {
        $params['status'] = $params['state'] == 1?'已处理':'已拒绝';
        $templateParams = array_merge($params,['type'=>$params['type'],'templateAttr'=>$params['templateAttr'],'openid'=>$params['openid']]);
        (new \addons\service\library\MiniSms())->sendMessage($templateParams);
        return true;
    }


    public static function createRefundTemplateParams($params)
    {
        $templateOrder = self::refundOrderTemplate($params);
        $templateParams = array_merge($templateOrder,['id'=>$params['id'],'type'=>$params['type'],'templateAttr'=>$params['templateAttr'],'openid'=>$params['openid'],'note'=>$params['note']]);
        (new \addons\service\library\MiniSms())->sendMessage($templateParams);
        return true;
    }

    public static function refundOrderTemplate($params)
    {
        $refundOrder =RefundOrder::where('order_id',$params['id'])->field('id,state')->find();
        $params['cate'] = OrderDetail::where('order_id',$params['id'])->value('name');
        $params['status'] = $refundOrder?$refundOrder['state'] == 1?'审核通过':'审核拒绝':'审核通过';
        $params['time'] = time();
        return $params;
    }


    public static function accept($params)
    {
        $order = self::where(['status'=>1,'id'=>$params['id']])->field('id,user_id,skill_id,is_pool,starttime,actendtime,to_shop')->find();
        if(!$order)
        {
            throw new Exception('当前订单无法选取接单,请联系管理员');
        }
        OrderLog::create(['order_id'=>$order['id'],'user_id'=>$order['user_id'],'type'=>2,'content'=>'订单已被服务者接取']);
        $update['accepttime']= time();
        $update['status'] = 2;
        if($order['is_pool'] == 1)
        {
            $update['is_pool'] = 0;
            $update['skill_id'] = $params['skill_id'];
            $update['shop_id'] = $params['shop_id'];
            $exist = SkillTime::where(['skill_id'=>$params['skill_id'],'state'=>['in',[1,2]],'starttime'=>['between',[$order['starttime'],$order['actendtime']]]])->value('id');
            if($exist)
            {
                throw new Exception('当前项目时间区间有被预约');
            }
            SkillTime::updateSkillTime(['skill_id'=>$params['skill_id'],'starttime'=>$order['starttime'],'actendtime'=>$order['actendtime']],1);
            Skill::where('id',$params['skill_id'])->inc('salenums')->update();
        }
        self::where(['id'=>$order['id']])->update($update);
        $userOpenid = UserInfo::getOpenid($order['user_id'],0);
        self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>0,'note'=>'有问题请联系客服','templateAttr'=>'user_notice_template','openid'=>$userOpenid]);
        return true;
    }

    public static function createOrderTemplateParams($order)
    {
        $templateOrder = self::getTemplateOrderInfo($order['id']);
        $templateParams = array_merge($templateOrder,['id'=>$order['id'],'type'=>$order['type'],'templateAttr'=>$order['templateAttr'],'openid'=>$order['openid']]);
        (new \addons\service\library\MiniSms())->sendMessage($templateParams);
        return true;
    }

    public static function go($params)
    {
        $order = self::where(['status'=>2,'id'=>$params['id']])->field('id,user_id,to_shop,skill_id')->find();
        if(!$order)
        {
            throw new Exception('当前订单状态异常');
        }
        OrderLog::create(['order_id'=>$params['id'],'user_id'=>$order['user_id'],'type'=>3,'content'=>'服务人员已出发']);
        self::where(['id'=>$params['id']])->update(['reachtime'=>time(),'status'=>3]);
        return true;
    }

    public static function reach($params)
    {
        $order = self::where(['status'=>3,'id'=>$params['id']])->field('id,user_id,to_shop')->find();
        if(!$order)
        {
            throw new Exception('当前订单状态异常');
        }
        OrderLog::create(['order_id'=>$params['id'],'user_id'=>$order['user_id'],'type'=>4,'content'=>'服务人员已到达']);
        self::where(['id'=>$params['id']])->update(['reachtime'=>time(),'status'=>4,'reach_images'=> $params['reach_images'] ?? '']);
        return true;
    }

    public static function skillStart($params)
    {
        $order = self::where(['status'=>4,'id'=>$params['id']])->field('id,user_id,to_shop,skill_id')->find();
        if(!$order)
        {
            throw new Exception('当前订单状态异常');
        }
        OrderLog::create(['order_id'=>$params['id'],'user_id'=>$order['user_id'],'type'=>5,'content'=>'服务人员已开始服务']);
        self::where(['id'=>$params['id']])->update(['servicetime'=>time(),'status'=>5]);
        $userOpenid = UserInfo::getOpenid($order['user_id'],0);
        Order::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'note'=>'有问题请联系客服','type'=>0,'templateAttr'=>'user_order_template','openid'=>$userOpenid]);
        return true;
    }

    public static function skillFinish($params)
    {
        $order = self::where(['status'=>['in',[2,5]],'id'=>$params['id']])->field('id,to_shop,user_id,skill_id,shop_id,goods_total_price,shop_id,payprice,settle_price,travel_price,price,sumprice,premium_price,coupon_price,add_price')->find();
        if(!$order)
        {
            throw new Exception('当前订单状态异常，无法确认完成');
        }
        //更新订单，进行订单待结算
        self::where(['id'=>$params['id']])->update(['status'=>6,'finish_images'=>isset($params['finish_images'])?$params['finish_images']:'','finishtime'=>time()]);
        self::orderFinish($order);
        $userOpenid = UserInfo::getOpenid($order['user_id'],0);
        self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>0,'note'=>'有问题请联系客服','templateAttr'=>'order_finish_template','openid'=>$userOpenid]);
        if($order['shop_id'])
        {
            $shopOpenid = UserInfo::getOpenid($order['shop_id'],2);
            self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_finish_template','openid'=>$shopOpenid]);
        }
        
        // 服务者星级升级
        $service = model('app\api\model\service\Skill')->where(['id'=>$order['skill_id']])->field('level,level_num')->find();
        $level = $service['level'];
        $completed = $service['level_num'];  // 当前等级已完成的订单数
        // 升级规则
        $upgradeRules = model('app\admin\model\service\skill\Level')->where(['state'=>1])->column('level,limit');
        $maxLevel = model('app\admin\model\service\skill\Level')->where(['state'=>1])->order('level desc')->value('level');
        // 订单完成数+1
        $newCompleted = $completed + 1;
        $newLevel = $level;
        // 非最高级时检查升级条件
        if ($level < $maxLevel) {
            // 检查是否达到当前等级升级要求
            if (isset($upgradeRules[$level]) && $newCompleted >= $upgradeRules[$level]) {
                $newLevel = $level + 1;
                $newCompleted = 0; // 升级后重置完成数
            }
        }
        // 更新服务者数据
        $updateData = [
            'level'      => $newLevel,
            'level_num'  => $newCompleted,
            'updatetime' => time()
        ];
        $result = model('app\api\model\service\Skill')->where('id', $order['skill_id'])->update($updateData);
        if (!$result) {
            throw new Exception('服务者数据更新失败');
        }
        
        
        
        return true;
    }

    public static function orderFinish($order)
    {
        OrderLog::create(['order_id'=>$order['id'],'user_id'=>$order['user_id'],'type'=>6,'content'=>'服务人员已完成服务']);
        $settleDay = $order['shop_id']?Shop::getSettleDay($order['shop_id']):ProjectConfig::getProjectConfig('settle_day');
        $settletime = $settleDay*86400+time();
        $totalPrice = bcadd(($order['goods_total_price']+$order['premium_price']),$order['add_price'],2);
        $settlePrice =$order['coupon_price'] > 0 ?bcsub($totalPrice,$order['coupon_price'],2): $totalPrice;
        $update = ['is_settle'=>1,'settletime'=>$settletime,'settle_price'=>$settlePrice];
        if($order['skill_id'])
        {
            $update['skill_percent'] = Skill::where('id',$order['skill_id'])->value('percent');
        }
        if($order['shop_id'])
        {
            $update['shop_percent'] = Shop::where('id',$order['shop_id'])->value('percent');
        }
        self::where(['id'=>$order['id']])->update($update);
        return true;
    }

    public static function checkOrder($order)
    {
        if(!$order)
        {
            throw new Exception('订单信息异常,无法核销');
        }
        self::where(['id'=>$order['id']])->update(['status'=>6,'finishtime'=>time()]);
        self::orderFinish($order);
        $shopOpenid = UserInfo::getOpenid($order['shop_id'],2);
        self::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_order_template','openid'=>$shopOpenid]);
        return true;
    }

    public function adddetail()
    {
        return $this->hasMany('AddOrderDetail','order_id');
    }

    public function detail()
    {
        return $this->hasMany('OrderDetail','order_id');
    }
}
